﻿#region

using System;
using System.Transactions;
using AopAndIocDemo.Biz.Logging;
using PostSharp.Aspects;
using PostSharp.Aspects.Dependencies;

#endregion

namespace AopAndIocDemo.Biz.Aspect
{
    [Serializable]
    [AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.After, typeof (LogAspect))]
    public sealed class RunInTransactionAspect : OnMethodBoundaryAspect
    {
        private static readonly LoggerService LoggerService = new LoggerService();
        [NonSerialized] private TransactionScope _transactionScope;

        public override void OnEntry(MethodExecutionArgs args)
        {
            _transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew);
        }

        public override void OnSuccess(MethodExecutionArgs args)
        {
            _transactionScope.Complete();
        }

        public override void OnException(MethodExecutionArgs args)
        {
            args.FlowBehavior = FlowBehavior.Continue;
            Transaction.Current.Rollback();

            string msg = String.Format("Transaction Was Unsuccessful! Exception in :[{0}],Message:[{1}]", args.Method,
                args.Exception.Message);
            //LoggHelper.WriteLog(LogType.Error, msg);
            LoggerService.Info(msg);
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            _transactionScope.Dispose();
        }
    }
}